package org.example.base;

import sun.misc.Unsafe;
import java.lang.reflect.Field;
public class CASTest {
    private Long offset;
    private Long state = 0L;

    public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException {

        // 获取unsafe实例
        Field f = Unsafe.class.getDeclaredField("theUnsafe");
        f.setAccessible(true);
        Unsafe unsafe = (Unsafe) f.get(null);

        CASTest casTest = new CASTest();
        casTest.offset = unsafe.objectFieldOffset(casTest.getClass().getDeclaredField("state"));
        boolean b = unsafe.compareAndSwapLong(casTest.state, casTest.offset, 0, 1);

        System.out.println("b= " + b);
        System.out.println("state= " + casTest.state);
    }
}
